# 数据库备份脚本
# 使用方法: .\scripts\backup.ps1

$timestamp = Get-Date -Format "yyyyMMdd-HHmmss"
$backupDir = "backups"
$dbPath = "packages/server/data/database.sqlite"

# 创建备份目录
if (!(Test-Path $backupDir)) {
    New-Item -ItemType Directory -Path $backupDir | Out-Null
    Write-Host "✅ 创建备份目录: $backupDir" -ForegroundColor Green
}

# 检查数据库文件是否存在
if (!(Test-Path $dbPath)) {
    Write-Host "❌ 数据库文件不存在: $dbPath" -ForegroundColor Red
    exit 1
}

# 执行备份
try {
    $backupFile = "$backupDir/database-$timestamp.sqlite"
    Copy-Item $dbPath -Destination $backupFile
    
    $fileSize = (Get-Item $backupFile).Length / 1KB
    Write-Host "✅ 备份完成: $backupFile ($('{0:N2}' -f $fileSize) KB)" -ForegroundColor Green
    
    # 清理超过30天的备份
    Get-ChildItem $backupDir -Filter "database-*.sqlite" | 
        Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-30) } | 
        ForEach-Object {
            Remove-Item $_.FullName
            Write-Host "🧹 清理旧备份: $($_.Name)" -ForegroundColor Yellow
        }
    
} catch {
    Write-Host "❌ 备份失败: $_" -ForegroundColor Red
    exit 1
}

